package models

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Username   string `json:"username" form:"username" gorm:"type:varchar(20);not null; unique" binding:"required"`
	Password   string `json:"password" form:"password" gorm:"type:varchar(20);not null"  binding:"required"`
	UserOthers string `json:"userothers" form:"userothers" gorm:"type:varchar(20);not null"  binding:"required"`
	IsDel      bool   `json:"isdel" form:"isdel" gorm:"type:boolean default false;"`
}

func getJson4(c *gin.Context) User {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)
	username := json["username"]
	password := json["password"]
	userothers := json["userothers"]
	user := User{
		Username:   username,
		Password:   password,
		UserOthers: userothers,
	}
	return user
}

// 获取单个用户
// func GetUser(c *gin.Context) (User, error) {
// 	user := getJson4(c)
// 	ok, err := cacher.Exists(user.Username)
// 	if err != nil {
// 		log.Fatalf("redis error, err:%v", err)
// 	}
// 	if ok {
// 		pwd, err := cacher.GetString(user.Username)
// 		if pwd == user.Password {
// 			return User{
// 				Username: user.Username,
// 				Password: user.Password,
// 			}, err
// 		}
// 	} else {
// 		err := db.Table("users").Where("username = ? AND password = ?", user.Username, user.Password).First(&user).Error
// 		if err == nil {
// 			// 在 redis 中设置该 用户名和密码 下次直接从 redis 中找
// 			cacher.Do("Set", user.Username, user.Password)
// 		}
// 		return user, err
// 	}
// 	return User{}, nil
// }

// 获取所有的 User
func GetAllUser() ([]User, int64, error) {
	var userdata []User
	err := db.Table("users").Where("is_del = false").Find(&userdata).Error
	totle := int64(len(userdata))
	return userdata, totle, err
}

// 增加员工的信息
func AddUser(c *gin.Context) (User, error) {
	user := getJson4(c)
	err := db.Table("users").Create(&user).Error
	return user, err
}

// 修改员工信息
func UpdateUser(c *gin.Context) (User, error) {
	user := getJson4(c)
	err := db.Table("users").Where("username = ?", user.Username).Updates(&user).Error
	return user, err
}

// 删除员工
func DelUser(c *gin.Context) error {
	id := c.Params.ByName("id")
	err := db.Table("users").Where("username = ?", id).Update("is_del", true).Error
	return err
}
